package user.com.interceptor;

import com.constant.ResponseDataConstant;
import com.google.gson.Gson;
import com.responseData.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import user.com.entity.Dto.UserLoginDto;
import user.com.utils.RedisUtils;
import user.com.utils.UserInfoUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 *
 */
@Slf4j
@Component
public class UserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        String userId = request.getHeader("userId");
        Gson gson = new Gson();

//        if(token == null || userId == null){
////            formatResp(response,
////                    gson.toJson(ResponseData.unusualCustomize(ResponseDataConstant.LOGIN_TIMEOUT,"未登录不能操作")));
////            return false;
////        }

        try {
             Object obj = RedisUtils.redis.opsForValue().get(token);
            //判断token是否存在
            if (obj == null) {
                formatResp(response,
                        gson.toJson(ResponseData.unusualCustomize(ResponseDataConstant.LOGIN_TIMEOUT,"未登录不能操作")));
                return false;
            }
            UserLoginDto dto = gson.fromJson(String.valueOf(obj),UserLoginDto.class);

            //携带中的userId是否与token中保持一致
            if(!userId.equals(dto.getUserId())){
                formatResp(response,
                        gson.toJson(ResponseData.unusualCustomize(ResponseDataConstant.USER_USUAL,"账号异常")));
                return false;
            }
            UserInfoUtils.add(dto);
        } catch (Exception e) {
            e.printStackTrace();
            formatResp(response,
                    new Gson().toJson(ResponseData.unusualCustomize(ResponseDataConstant.ERROR,"出现未知错误")));

            return false;
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserInfoUtils.remove();
        log.info("threadLocal 移除");
    }

    public void formatResp(HttpServletResponse resp , String json) throws IOException {
//        resp.setContentType("text/json;charset=UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().append(json);
    }
}
